package com.xjd.edu.toolkit.metrics.feign;

import feign.Client;
import io.micrometer.core.instrument.MeterRegistry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * @author wangyu
 * @since 2023/2/8
 */
@Slf4j
public class FeignClientBeanPostProcessor implements BeanPostProcessor {

    private volatile boolean injected = false;

    private final MeterRegistry registry;

    public FeignClientBeanPostProcessor(MeterRegistry registry) {
        this.registry = registry;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (!injected && bean instanceof Client) {
            injected = true;
            log.info("Feign Client Metrics, Bean name: {}, Bean type: {} ", beanName, bean.getClass().getName());
            return new FeignMeteredClient((Client) bean, registry);
        }
        return bean;
    }

}
